import ReactEcharts from 'echarts-for-react';
import {Button, Card, Col, DatePicker, Form, message, Radio, Row} from 'antd';
import React, {useEffect, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import styles from './style.less';
import moment from 'moment';
import {statsAmountByMonth, statsRatioByProduct} from '@/services/finance'


const TableList = () => {
  const [totalData, setTotalData] = useState([])
  const [outAmountOption, setOutAmountOption] = useState({
    tooltip: {
      trigger: 'axis',
      axisPointer: {            // 坐标轴指示器，坐标轴触发有效
        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: [],
        axisTick: {
          alignWithLabel: true
        }
      }
    ],
    yAxis: [
      {
        type: 'value'
      }
    ],
    series: [
      {
        name: '直接访问',
        type: 'bar',
        barWidth: '60%',
        data: []
      }
    ]
  })
  const [outAreaOption, setOutAreaOption] = useState({
    tooltip: {
      trigger: 'axis',
      axisPointer: {            // 坐标轴指示器，坐标轴触发有效
        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: [],
        axisTick: {
          alignWithLabel: true
        }
      }
    ],
    yAxis: [
      {
        type: 'value'
      }
    ],
    series: [
      {
        name: '直接访问',
        type: 'bar',
        barWidth: '60%',
        data: []
      }
    ]
  })
  const [outQualityOption, setOutQualityOption] = useState({
    tooltip: {
      trigger: 'axis',
      axisPointer: {            // 坐标轴指示器，坐标轴触发有效
        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: [],
        axisTick: {
          alignWithLabel: true
        }
      }
    ],
    yAxis: [
      {
        type: 'value'
      }
    ],
    series: [
      {
        name: '直接访问',
        type: 'bar',
        barWidth: '60%',
        data: []
      }
    ]
  })
  const [outAmountRatioOption, setOutAmountRatioOption] = useState({
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top: 'center',
      orient: 'vertical',
      right: 0
    },
    series: [
      {
        name: '访问来源',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '20',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: []
      }
    ]
  })
  const [outAreaRatioOption, setOutAreaRatioOption] = useState({
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top: 'center',
      orient: 'vertical',
      right: 0
    },
    series: [
      {
        name: '访问来源',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '20',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: []
      }
    ]
  })
  const [outQualityRatioOption, setOutQualityRatioOption] = useState({
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top: 'center',
      orient: 'vertical',
      right: 0
    },
    series: [
      {
        name: '访问来源',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '20',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: []
      }
    ]
  })
  const [priceType, setPriceType] = useState(1)
  const [sizeType, setSizeType] = useState(1)
  const [quantityType, setQuantityType] = useState(1)
  const {RangePicker} = DatePicker

  const initRatioOption = (val) => {
    setOutAmountRatioOption({
      tooltip: {
        trigger: 'item',
        formatter: '{a0}<br />{b0}: {d0}%'
      },
      legend: {
        top: 'center',
        orient: 'vertical',
        right: 0
      },
      series: [
        {
          name: '产品金额占比',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '20',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: val.priceRatio.map(item => {
            return {
              value: item.priceRatio,
              name: item.productCode
            }
          })
        }
      ]
    })
    setOutAreaRatioOption({
      tooltip: {
        trigger: 'item',
        formatter: '{a0}<br />{b0}: {d0}%'
      },
      legend: {
        top: 'center',
        orient: 'vertical',
        right: 0
      },
      series: [
        {
          name: '产品平米数占比',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '20',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: val.sqmRatio.map(item => {
            return {
              value: item.sqmRatio,
              name: item.productCode
            }
          })
        }
      ]
    })
    setOutQualityRatioOption({
      tooltip: {
        trigger: 'item',
        formatter: '{a0}<br />{b0}: {d0}%'
      },
      legend: {
        top: 'center',
        orient: 'vertical',
        right: 0
      },
      series: [
        {
          name: '产品数量占比',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '20',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: val.numRatio.map(item => {
            return {
              value: item.numRatio,
              name: item.productCode
            }
          })
        }
      ]
    })
  }

  // 价格柱状图
  const renderAmountBarOption = (type) => {
    const chartType = type ? type : priceType
    if (chartType === 1) {
      const xData = [];
      totalData.forEach(item => {
        if (xData.indexOf(item.dataMonth) < 0) {
          xData.push(item.dataMonth)
        }
      })
      const yData = xData.map(i => 0);
      xData.forEach((x, index) => {
        totalData.forEach(item => {
          if (x === item.dataMonth) {
            yData[index] += item.shippedPrice
          }
        })
      })
      setOutAmountOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: xData,
            axisTick: {
              alignWithLabel: true
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '元',
          }
        ],
        series: [
          {
            name: '出货金额',
            type: 'bar',
            barMaxWidth: 40,
            data: yData
          }
        ]
      })

    } else {
      const xData = [];
      totalData.forEach(item => {
        if (xData.indexOf(item.dataMonth) < 0) {
          xData.push(item.dataMonth)
        }
      })
      const productData = [];
      totalData.forEach(item => {
        if (productData.indexOf(item.productCode) < 0) {
          productData.push(item.productCode)
        }
      })
      const seriesData = productData.map(prd => {
        const yData = xData.map(i => 0);
        xData.forEach((x, index) => {
          totalData.forEach(item => {
            if (item.productCode === prd && item.dataMonth === x) {
              yData[index] = item.shippedPrice
            }
          })
        })
        return {
          name: `${prd}`,
          type: 'bar',
          barMaxWidth: 40,
          data: yData
        }
      });
      setOutAmountOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        legend: {
          data: productData
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: xData,
            axisTick: {
              alignWithLabel: true
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '元'
          }
        ],
        series: seriesData
      })
    }
  }

  // 面积柱状图
  const renderSizeBarOption = (type) => {
    const chartType = type ? type : sizeType
    if (chartType === 1) {
      const xData = [];
      totalData.forEach(item => {
        if (xData.indexOf(item.dataMonth) < 0) {
          xData.push(item.dataMonth)
        }
      })
      const yData = xData.map(i => 0);
      xData.forEach((x, index) => {
        totalData.forEach(item => {
          if (x === item.dataMonth) {
            yData[index] += item.shippedSqm
          }
        })
      })
      setOutAreaOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: xData,
            axisTick: {
              alignWithLabel: true
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: 'm²'
          }
        ],
        series: [
          {
            name: '出货平米数',
            type: 'bar',
            barMaxWidth: 40,
            data: yData
          }
        ]
      })

    } else {
      const xData = [];
      totalData.forEach(item => {
        if (xData.indexOf(item.dataMonth) < 0) {
          xData.push(item.dataMonth)
        }
      })
      const productData = [];
      totalData.forEach(item => {
        if (productData.indexOf(item.productCode) < 0) {
          productData.push(item.productCode)
        }
      })
      const seriesData = productData.map(prd => {
        const yData = xData.map(i => 0);
        xData.forEach((x, index) => {
          totalData.forEach(item => {
            if (item.productCode === prd && item.dataMonth === x) {
              yData[index] = item.shippedSqm
            }
          })
        })
        return {
          name: `${prd}`,
          type: 'bar',
          barMaxWidth: 40,
          data: yData
        }
      });
      setOutAreaOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        legend: {
          data: productData
        },
        xAxis: [
          {
            type: 'category',
            data: xData,
            axisTick: {
              alignWithLabel: true
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: 'm²'
          }
        ],
        series: seriesData
      })
    }
  }
  // 数量柱状图
  const renderQuantityBarOption = (type) => {
    const chartType = type ? type : quantityType
    if (chartType === 1) {
      const xData = [];
      totalData.forEach(item => {
        if (xData.indexOf(item.dataMonth) < 0) {
          xData.push(item.dataMonth)
        }
      })
      const yData = xData.map(i => 0);
      xData.forEach((x, index) => {
        totalData.forEach(item => {
          if (x === item.dataMonth) {
            yData[index] += item.shippedNum
          }
        })
      })
      setOutQualityOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: xData,
            axisTick: {
              alignWithLabel: true
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: 'pcs'
          }
        ],
        series: [
          {
            name: '出货数量',
            type: 'bar',
            barMaxWidth: 40,
            data: yData
          }
        ]
      })

    } else {
      const xData = [];
      totalData.forEach(item => {
        if (xData.indexOf(item.dataMonth) < 0) {
          xData.push(item.dataMonth)
        }
      })
      const productData = [];
      totalData.forEach(item => {
        if (productData.indexOf(item.productCode) < 0) {
          productData.push(item.productCode)
        }
      })
      const seriesData = productData.map(prd => {
        const yData = xData.map(i => 0);
        xData.forEach((x, index) => {
          totalData.forEach(item => {
            if (item.productCode === prd && item.dataMonth === x) {
              yData[index] = item.shippedNum
            }
          })
        })
        return {
          name: `${prd}`,
          type: 'bar',
          barMaxWidth: 40,
          data: yData
        }
      });
      setOutQualityOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        legend: {
          data: productData
        },
        xAxis: [
          {
            type: 'category',
            data: xData,
            axisTick: {
              alignWithLabel: true
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: 'pcs'
          }
        ],
        series: seriesData
      })
    }
  }

  useEffect(() => {
    renderAmountBarOption()
  }, [totalData])
  useEffect(() => {
    renderSizeBarOption()
  }, [totalData])
  useEffect(() => {
    renderQuantityBarOption()
  }, [totalData])

  const queryData = async (param) => {
    await statsAmountByMonth({
      ...param
    }).then(res => {
      if (res && res.status === '0') {
        setTotalData(res.data)

      } else {
        message.error(res.message)
      }

    });
  }

  const queryRatio = async (param) => {
    await statsRatioByProduct({
      ...param
    }).then(res => {
      if (res && res.status === '0') {
        const compare = function (prop) {
          return function (obj1, obj2) {
            const val1 = obj1[prop];
            const val2 = obj2[prop];
            if (val1 < val2) {
              return 1;
            } else if (val1 > val2) {
              return -1;
            } else {
              return 0;
            }
          }
        }
        const priceRatioTemp = res.data.sort(compare('priceRatio'));
        const numRatioTemp = res.data.sort(compare('numRatio'));
        const sqmRatioTemp = res.data.sort(compare('sqmRatio'));
        const priceRatio = [];
        const priceOtherItem = {
          'productCode': '其它',
          'priceRatio': 0
        };
        priceRatioTemp.forEach((item, idx) => {
          if (idx < 5) {
            priceRatio.push(item)
          } else {
            priceOtherItem.priceRatio += item.priceRatio
          }
        })
        if (priceOtherItem.priceRatio > 0) {
          priceRatio.push(priceOtherItem)
        }

        const numRatio = [];
        const numOtherItem = {
          'productCode': '其它',
          'numRatio': 0
        };
        numRatioTemp.forEach((item, idx) => {
          if (idx < 5) {
            numRatio.push(item)
          } else {
            numOtherItem.numRatio += item.numRatio
          }
        })
        if (numOtherItem.numRatio > 0) {
          numRatio.push(numOtherItem)
        }

        const sqmRatio = [];
        const sqmOtherItem = {
          'productCode': '其它',
          'sqmRatio': 0
        };
        sqmRatioTemp.forEach((item, idx) => {
          if (idx < 5) {
            sqmRatio.push(item)
          } else {
            sqmOtherItem.sqmRatio += item.sqmRatio
          }
        })
        if (sqmOtherItem.sqmRatio > 0) {
          sqmRatio.push(sqmOtherItem)
        }


        initRatioOption({
          'priceRatio': priceRatio,
          'sqmRatio': sqmRatio,
          'numRatio': numRatio
        })
      } else {
        message.error(res.message)
      }
    })
  }
  useEffect(() => {
    queryData({
      startDate: moment().subtract(5, "months").format('YYYYMM'),
      endDate: moment().format('YYYYMM')
    })
  }, [])
  useEffect(() => {
    queryRatio({
      startDate: moment().subtract(5, "months").format('YYYYMM'),
      endDate: moment().format('YYYYMM')
    })
  }, [])

  const onPriceChange = (e) => {
    setPriceType(e.target.value)
    renderAmountBarOption(e.target.value)
  }
  const onSizeChange = (e) => {
    setSizeType(e.target.value)
    renderSizeBarOption(e.target.value)
  }
  const onQuantityChange = (e) => {
    console.log(e.target.value)
    setQuantityType(e.target.value)
    renderQuantityBarOption(e.target.value)
  }

  return (
    <PageContainer>
      <Card className={styles.monthlySearch}>
        <Form
          layout="inline"
          onFinish={async (values) => {
            const param = values.date ? {
              productCode: values.productCode,
              startDate: moment(values.date[0]).format("YYYYMM"),
              endDate: moment(values.date[1]).format("YYYYMM"),
            } : {
              productCode: values.productCode,
            }
            await queryData(param)
            await queryRatio(param)
          }}
          initialValues={{
            date: [moment().subtract(5, "months"), moment()]
          }}
        >
          <Form.Item
            label={'日期'}
            name={'date'}
          >
            <RangePicker picker="month"/>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <Card style={{marginTop: 10}}>
        <Row>
          <Col span={16}>
            <Card style={{width: '98%'}} title={'出货金额'} extra={
              <Radio.Group defaultValue={1} buttonStyle="solid" onChange={(e) => onPriceChange(e)}>
                <Radio.Button value={1}>总体</Radio.Button>
                <Radio.Button value={2}>详情</Radio.Button>
              </Radio.Group>}>
              <ReactEcharts notMerge={true}
                            option={outAmountOption}/>
            </Card>
          </Col>
          <Col span={8}>
            <Card style={{width: '100%'}} title={'产品金额占比'}>
              <ReactEcharts option={outAmountRatioOption}/>
            </Card>
          </Col>
        </Row>
      </Card>
      <Card style={{marginTop: 10}}>
        <Row>
          <Col span={16}>
            <Card style={{width: '98%'}} title={'出货平米数'} extra={
              <Radio.Group defaultValue={1} buttonStyle="solid" onChange={(e) => onSizeChange(e)}>
                <Radio.Button value={1}>总体</Radio.Button>
                <Radio.Button value={2}>详情</Radio.Button>
              </Radio.Group>}>
              <ReactEcharts notMerge={true}
                            option={outAreaOption}/>
            </Card>
          </Col>
          <Col span={8}>
            <Card style={{width: '100%'}} title={'产品平数占比'}>
              <ReactEcharts option={outAreaRatioOption}/>
            </Card>
          </Col>
        </Row>
      </Card>
      <Card style={{marginTop: 10}}>
        <Row>
          <Col span={16}>
            <Card style={{width: '98%'}} title={'出货数量'} extra={
              <Radio.Group defaultValue={1} buttonStyle="solid" onChange={(e) => onQuantityChange(e)}>
                <Radio.Button value={1}>总体</Radio.Button>
                <Radio.Button value={2}>详情</Radio.Button>
              </Radio.Group>}>
              <ReactEcharts notMerge={true}
                            option={outQualityOption}/>
            </Card>
          </Col>
          <Col span={8}>
            <Card style={{width: '100%'}} title={'产品数量占比'}>
              <ReactEcharts option={outQualityRatioOption}/>
            </Card>
          </Col>
        </Row>
      </Card>
    </PageContainer>
  );
};

export default TableList;
